/*
 * @Date: 2022-02-23 10:34:46
 * @LastEditors: 春贰
 * @gitee: https://gitee.com/chun22222222
 * @github: https://github.com/chun222
 * @Desc:
 * @LastEditTime: 2022-07-08 11:03:08
 * @FilePath: \server\system\service\BaseService\login.go
 */
package BaseService

import (
	"fmt"

	"go2admin_pure/system/core/cache"
	"go2admin_pure/system/core/db"
	"go2admin_pure/system/core/ws"
	"go2admin_pure/system/model/DbModel"
	"go2admin_pure/system/util/sli"
	"go2admin_pure/system/util/sys"
	"gorm.io/gorm"
)

type LoginService struct{}

func (loginService *LoginService) Login(u *DbModel.SysUser) (err error, user *DbModel.SysUser) {
	u.Password = sys.EncryptPass(u.Password)
	err = db.Instance().Where("login_name = ? AND password = ?", u.LoginName, u.Password).Preload("Permissions", func(db *gorm.DB) *gorm.DB {
		return db.Where("status = ?", 1).Order("sort asc")
	}).Preload("Roles.Permissions", func(db *gorm.DB) *gorm.DB {
		return db.Where("status = ?", 1).Order("sort asc")
	}).First(&user).Error
	user.Permissions = mergePermissions(user)
	//密码正确
	if err == nil {
		if u.Kick == 99 {
			//强制下线
			ws.SendMsg(int(user.ID), "kick offline", ws.TypeKick)
			user.Kick = 1
		} else {
			fmt.Println("login:", ws.OnlineIds())
			if sli.InSlice(int(user.ID), ws.OnlineIds()) {
				//询问是否下线
				user.Kick = 2
			} else {
				user.Kick = 1
			}

		}

		//缓存
		cache.Set(user.ID, user.Permissions, 0)

	}

	return err, user

}

//根据id获取权限
func (loginService *LoginService) GetPerById(id uint) (err error, user *DbModel.SysUser) {

	err = db.Instance().Preload("Permissions", func(db *gorm.DB) *gorm.DB {
		return db.Where("status = ?", 1).Order("sort asc")
	}).Preload("Roles.Permissions", func(db *gorm.DB) *gorm.DB {
		return db.Where("status = ?", 1).Order("sort asc")
	}).First(&user, id).Error
	user.Permissions = mergePermissions(user)
	//缓存
	cache.Set(user.ID, user.Permissions, 0)
	return err, user
}

//合并权限
func mergePermissions(u *DbModel.SysUser) []DbModel.SysPermission {
	r := make([]DbModel.SysPermission, 0)
	//fmt.Printf("%+v", u.Permissions)
	for _, v := range u.Permissions {
		r = append(r, v)
	}

	for _, _roles := range u.Roles {
		for _, v := range _roles.Permissions {
			r = append(r, v)
		}
	}

	//去重
	result := make([]DbModel.SysPermission, 0)
	temp := map[string]byte{}
	for _, value := range r {
		l := len(temp)
		temp[value.Name] = 0
		if len(temp) != l {
			result = append(result, value)
		}
	}
	return result

}
